
package org.dcarew.halostatus;

import org.dcarew.halostatus.utils.LabelContributionItem;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.action.StatusLineManager;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IStartup;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.internal.WorkbenchWindow;

/**
 * The IStartup item for the Halo status project. This is run an Eclipse startup and adds our
 * contribution item to the status line.
 * 
 * @author Devon Carew
 */
public class HaloStatusStartup
	implements IStartup
{

	public HaloStatusStartup()
	{
		
	}

	/**
	 * Called by the workspace after general statup.
	 */
	public void earlyStartup()
	{
		PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
		    public void run() {
		    	addStatusLineContribution();
		    }
		});
	}
	
	/**
	 * Adds the cruise control status line contrubution. This must be called from the display thread.
	 */
	private void addStatusLineContribution()
	{
		IWorkbenchWindow[] windows = PlatformUI.getWorkbench().getWorkbenchWindows();
		
		if (windows.length < 1)
			throw new IllegalStateException("should be at least one workbench window");
		
		WorkbenchWindow window = (WorkbenchWindow)windows[0];
		
		final StatusLineManager statusLineManager = window.getStatusLineManager();
		
		final LabelContributionItem label = new LabelContributionItem(HaloStatusPlugin.PLUGIN_ID + ".statusContribution", 7);
		
		setHaloStatus(label, HaloStatusPlugin.getPlugin().getPlayerCount());
		label.setImage(HaloStatusPlugin.getImage("resources/icons/halo1.gif"));
		
		statusLineManager.add(new Separator("halo"));
		statusLineManager.appendToGroup("halo", label);
		
    	statusLineManager.update(true);
    	
    	HaloStatusPlugin.getPlugin().getPreferenceStore().addPropertyChangeListener(new IPropertyChangeListener() {
			public void propertyChange(PropertyChangeEvent event) {
				if (HaloStatusPlugin.PLAYER_COUNT_PREF.equals(event.getProperty()))
					setHaloStatus(label, (String)event.getNewValue());
			}
    	});
	}
	
	private void setHaloStatus(final LabelContributionItem label, final String haloStatus)
	{
		Display.getDefault().asyncExec(new Runnable() {
			public void run() {
				label.setText(haloStatus);
				
				if (haloStatus.length() > 0)
					label.setTooltip(haloStatus + " players online");
				else
					label.setTooltip(" ");
			}
		});
	}
	
}
